<template>
    <div class="search-suggestion">
        <van-cell @click="$emit('search',item)" v-for="(item, index) in dataList.suggestions" :key="index" center icon="search">
            <template #title>
                <div v-html="highLight(item)"></div>
            </template>
        </van-cell>
    </div>
</template>

<script>
import { reactive, watch } from 'vue'
import { getSearchSuggesAPI } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'searchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const dataList = reactive({
      suggestions: []
    })
    const getSearchSugges = async (q) => {
      try {
        const { data } = await getSearchSuggesAPI(q)
        if (data.data.options[0] != null) {
          dataList.suggestions = data.data.options
        } else {
          dataList.suggestions = []
        }
      } catch (err) {
        console.log(err)
      }
    }

    //  debounced（防抖动）函数
    watch(() => props.searchText, debounce((newValue, oldValue) => {
      getSearchSugges(newValue)
    }, 300), { immediate: true })

    // 搜索匹配高亮
    const highLight = (text) => {
      if (text) {
        const str = `<span class="active">${props.searchText}</span>`
        // RegExp 正则表达式构造函数
        const reg = new RegExp(props.searchText, 'gi')
        return text.replace(reg, str)
      }
    }
    return {
      dataList,
      highLight
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
    :deep(.active) {
        color: #3296fa;
    }
}
</style>
